import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';

@Component({
  selector: 'app-rest-password',
  templateUrl: './rest-password.component.html',
  styles: [``]
})
export class RestPasswordComponent implements OnInit {
  public member: any = {
    newpswd: '',
    confirmpswd: '',
    disi: '',
    id: 0,
    token: '',
    ip: '127.0.0.1'
  };
  public errorMessage: string = '';

  constructor(
    private title: Title,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private memberService: MemberService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(false); //不显示全局的导航
    this.member.disi = this.activatedRoute.snapshot.queryParams['hash'] || '#';
    this.member.id = +(this.activatedRoute.snapshot.queryParams['id'] || 0);
    this.member.token = this.activatedRoute.snapshot.queryParams['token'] || '-';
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.member.ip=ipAddr);
  }

  ngOnInit(): void {
    this.title.setTitle('找回帐号密码:第二步');
  }

  public resetPassword(submitBtn: HTMLButtonElement): void {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '正在提交数据...');
    //
    if (!this.isContinue()) {
      this.errorMessage = '超时了或重要参数遗失';
      //
      submitBtn.disabled = false;
      submitBtn.setAttribute('value', '下一步');
      return;
    }

    this.memberService.resetAnonyPassword(this.member.id, this.member.newpswd, this.member.token, this.member.ip).subscribe({
      next: response => {
        //跳转:/member/restPswd/success
        this.router.navigate(['member', 'rsetPswd', 'success']);
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            this.errorMessage = (err.status == 417) ? '重置密码失败' : err.error;
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        //
        submitBtn.disabled = false;
        submitBtn.setAttribute('value', '下一步');
      },
      complete: () => { console.log('[RestPassword-CTL]Completed'); }
    });

  }

  private isContinue(): boolean {
    //BASE64解码
    let hv: string = window.atob(this.member.disi);
    let v: any = JSON.parse(hv) || {};
    if (!v.member || v.member !== this.member.id) {
      return false;
    }
    if (!v.token || v.token !== this.member.token) {
      return false;
    }
    if (!v.stamp) {
      return false;
    }
    if (this.member.newpswd && this.member.confirmpswd && this.member.confirmpswd == this.member.newpswd) {
      //86400
      return (this.util.getUnixStamp() - v.stamp <= 180);
    }
    return false;

  }
}
